<template>
  <Layout class="main" style="height: 100%">
    <Sider v-model="collapsed" :collapsed-width="0" :style="{overflow: 'hidden'}" :width="sure_width" class="left-sider" collapsible
           hide-trigger>
      <side-menu ref="sideMenu" :activeName="activeName" :collapsed="collapsed" :menu-list="menuList" :menuMode="menuMode"
                 :openNames="openNames" accordion
                 @on-select="turnToPage">
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con public-pc-style">
        </div>
      </side-menu>
    </Sider>
    <Layout>
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :message-unread-count="unreadCount" :user-avatar="userAvatar"/>
        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">

          <custom-bread-crumb :list="breadCrumbList" class="crumb" show-icon></custom-bread-crumb>
          <Content id="contentTop" class="content-wrapper">
            <keep-alive :include="cacheList">
              <router-view/>
            </keep-alive>
            <ABackTop :bottom="80" :height="100" :right="50" container=".content-wrapper"></ABackTop>
          </Content>
        </Layout>
      </Content>
      <PublicCheckPassword/>
    </Layout>
  </Layout>
</template>
<script>
import _ from 'lodash';
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import ABackTop from './components/a-back-top'
import Fullscreen from './components/fullscreen'
import ErrorStore from './components/error-store'
import customBreadCrumb from '@/components/main/components/header-bar/custom-bread-crumb/custom-bread-crumb';
import PublicCheckPassword from '@/components/publicCheckPassword/publicCheckPassword.vue';
import {mapMutations, mapActions, mapGetters} from 'vuex'
import {getNewTagList, routeEqual} from '@/libs/util'
import routers from '@/router/routers'
import until from '@/js/until.js'

import './main.less'

export default {
  name: 'Main',
  components: {
    SideMenu,
    HeaderBar,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
    customBreadCrumb,
    PublicCheckPassword,
  },
  data() {
    return {
      collapsed: false,
      isFullscreen: false,
      sure_width: this.getScreenIsSmall() ? document.body.offsetWidth : 200,
      menuMode: this.getScreenIsSmall() ? 'horizontal' : 'vertical',
      aboutLanguage: {
        languageType: this.$store.state.locale || 'zh-cn',
        languageArr: [
          {
            value: 'zh-cn',
            label: '中文',
          },
          {
            value: 'en',
            label: 'English',
          },
        ]
      },
      openNames: [],
      activeName: '',
    }
  },
  computed: {
    ...mapGetters([
      'errorCount',
      'getPublicSideMenu',
      'getLocale',
    ]),
    tagNavList() {
      return this.$store.state.app.tagNavList
    },
    tagRouter() {
      return this.$store.state.app.tagRouter
    },
    userAvatar() {
      return this.$store.state.user.avatarImgPath
    },
    cacheList() {
      const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
      return list
    },
    menuList() {

      // 如果是手风琴对应的页面则展开
      if (window.innerWidth >= 760) {
        this.openNames = this.getOpenName();
        this.$nextTick(() => {
          this.activeName = this.$route.name;
        })
      }

      return routers;
    },
    local() {
      return this.$store.state.app.local;
    },
    hasReadErrorPage() {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount() {
      return this.$store.state.user.unreadCount
    },
    breadCrumbList() {
      return this.$store.state.app.breadCrumbList
    },
  },
  methods: {
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setHomeRoute',
      'closeTag',
      'setCountryArr',
      'setpermissionsPage',
      'settabNum',
    ]),
    ...mapActions([
      'handleLogin',
      'getUnreadMessageCount'
    ]),
    turnToPage(route) {
      // 防止重复点击
      if (this.$route.name === route) return;
      // 切换国家start
      var list = [];
      this.menuList.forEach(item => {
        list = list.concat(item.children)
      });
      // list.forEach((item) => {
      //   if ((item.name) == route) {
      //     if(item.meta.country_arr){
      //       localStorage.setItem('permissionsPage', JSON.stringify(item.meta.permissionsPage));
      //       localStorage.setItem('autheCountry', item.meta.country_arr);
      //     }
      //
      //   }
      // })
      this.settabNum(0);
      // 切换国家end

      localStorage.setItem('tabNum',0) // 跳转页面时重置tabIndex

      let {name, params, query} = {}
      if (typeof route == 'string') name = route
      else {
        name = route.name
        params = route.params
        query = route.query
      }
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }

      this.$router.push({
        name,
        params,
        query
      })
      // until.phoneType() == 'PC' ? '' : this.collapsed = true
      until.phoneType() == 'PC' ? '' : this.collapsed = false
    },
    handleCollapsedChange(state) {
      this.collapsed = state
    },
    handleCloseTag(res, type, route) {
      if (type !== 'others') {
        if (type == 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick(item) {
      this.turnToPage(item)
    },
    handleScreen() {
      if (this.getScreenIsSmall()) {
        this.collapsed = false;
        this.menuMode = 'horizontal';
        this.sure_width = document.body.offsetWidth;
      } else {
        this.collapsed = false;
        this.menuMode = 'vertical';
        this.sure_width = 200;
      }
    },
    getScreenIsSmall() {
      if (window.innerWidth < 750) return true;
      return false;
    },
    changeLan(e) {
      this.$i18n.locale = e;
      this.$store.commit('SETLOCALE', e);
    },
    leftMenu() {
      let authList = [1,2,5,8,140,141];
      localStorage.setItem("authList", JSON.stringify(authList));
    },
    // 刚进入页面拿到openname，如果是手风琴页面则打开
    getOpenName() {
      try {
        let matched = this.$router.history.current.matched;
        matched = matched[0] || {};
        return [matched.name];
      } catch (e) {
        // console.log(e);
        return [];
      }
    },
  },
  watch: {
    '$route'(newRoute) {
      const {name, query, params, meta} = newRoute
      this.addTag({
        route: {name, query, params, meta},
        type: 'push'
      })
      this.setBreadCrumb(newRoute)
      this.$refs.sideMenu.updateOpenName(newRoute.name)
    },
    getLocale: function () {
      // title翻译
      try {
        const $globalI18n = this.$selfGlobal.$globalI18n;
        document.title = $globalI18n.tc(this.$router.history.current.meta.nameText);
      } catch (e) {
        console.log(e);
        document.title = 'admin';
      }
    }
  },
  created() {
    this.leftMenu();

  },
  mounted() {
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    // this.setTagNavList()
    this.setHomeRoute(routers)
    const {name, params, query, meta} = this.$route
    this.addTag({
      route: {name, params, query, meta}
    })
    this.setBreadCrumb(this.$route)
    // 设置初始语言
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name == this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      })
    }
    // 获取未读消息条数
    // this.getUnreadMessageCount()
    if (until.phoneType() != 'PC') {
      // this.collapsed = true;
      this.collapsed = false;
      this.sure_width = document.body.offsetWidth;
    }

    this.$nextTick(() => {
      // this.handleScreen()
      until.screenResize(() => {
        this.handleScreen();
      });
    });

  },
}
</script>
<style lang="scss" scoped>
.crumb {
  padding: 10px 0 10px;
  margin-left: 30px;
}

@media screen and (max-width: 759px) {
  .main {
    display: block;
  }
  .left-sider > > > .ivu-menu-item,
  .left-sider > > > .ivu-menu-submenu {
    display: inline-block;
    float: none;

    &:last-of-type {
      margin-right: 20px;
    }
  }
  .left-sider > > > .ivu-menu {
    overflow: auto;
    white-space: nowrap;
  }

  .ivu-layout {
    // height: calc(100% - 60px);
    height: 100%;
    min-height: 400px;
  }

  .left-sider,
  .left-sider > > > .ivu-menu,
  .left-sider > > > .ivu-menu-submenu {
    position: static;
  }

  // 页脚移动端
  .main > > > .ivu-page-item:hover {
    border-color: #dcdee2;
    color: #515a6e;
  }
  .main > > > .ivu-page-item:hover a {
    color: #515a6e;
  }
  // menu移动端
  .main > > > .ivu-menu-dark.ivu-menu-horizontal .ivu-menu-item:hover,
  .main > > > .ivu-menu-dark.ivu-menu-horizontal .ivu-menu-submenu:hover {
    color: rgba(255, 255, 255, 0.7);
  }

  .main > > > .ivu-menu-dark.ivu-menu-horizontal .ivu-menu-item-selected {
    color: #ffffff !important;
  }

  .main > > > .ivu-select-dropdown .ivu-menu-drop-list .ivu-menu-item-selected {
    color: #515a6e !important;
  }
  .main > > > .ivu-page .ivu-page-item-active {
    border-color: #2d8cf0;
  }

  .main > > > .ivu-page .ivu-page-item-active a {
    color: #2d8cf0;
  }

  .header-con{
    display: none;
  }

}

#main-footer {
  padding: 10px 0;
}

.ivu-back-top-show {
  bottom: 150px !important;
  right: 10px !important;
}
</style>
